﻿<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ApplicationProfile.ascx.cs" Inherits="CRMWeb.UserControls.ApplicationProfile" %>

<script src="/Scripts/jquery.formatCurrency-1.4.0.js"></script>
<script src="/Scripts/jquery.formatCurrency.all.js"></script>

<div id="appProfile" style="background-color: rgb(255,220,185)">
    <div class="top_section" style="vertical-align: middle">
        <table style="width: 100%">
            <tr>
                <td style="text-align: left; width: 20%">
                    <span id="spnNavigation"></span>
                </td>
                <td style="text-align: center; width: 35%">
                    <div id="spnFullName"></div>
                </td>
                <td style="text-align: right; width: 35%">
                    <a href="javascript:void(0)" class="easyui-linkbutton save_folderbtn" title="Save" iconcls="icon-ok" id="btnSave" onclick="saveAllData()">Save</a>

                  <%--  Hide this button 20140203 wade
                      <a href="javascript:void(0)" class="easyui-linkbutton" title="App-Form" iconcls="icon-remove" onclick="$('#wndRemoveAppForm').window('open')">Remove Dup</a>
                      
                      --%>
                    <input type="button" id="btnHidden" runat="server" title="Hidden Button" visible="false" />
                    <a id="btnDelete" title="Delete Application" href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" plain="true" onclick="$('#dlgDelApp').window('open')"></a>
                </td>
            </tr>
        </table>
    </div>
    <div class="topform_section">
        <div data-options="fit:true" class="client_infodiv">
            <div data-options="region:'west',split:true,border:false" class="equal_div" style="width: 38%;">
                <input type="hidden" id="hdnUserName" runat="server" />
                <input type="hidden" id="hdnVerification" runat="server" value="false" />
                <input type="hidden" id="hdnAssesment" runat="server" value="false" />
                <input type="hidden" id="hdnContactID" runat="server" />

                <input type="hidden" id="hdnSACC" runat="server" value="false" />
                <input type="hidden" id="hdnContract" runat="server" value="false" />
                <input type="hidden" id="hdnMC_status" runat="server">
                <input id="hdnEmail" type="hidden" />
                <input type="hidden" id="hdnMobile">
                <div style="float: left;">
                    <div class="fitem" style="float: left;">
                        <label>Desired Amount:</label>
                        <input id="txtapp_damount" oninput="changePrice();" type="text" style="width: 94px;" class="easyui-validatebox" />
                    </div>
                    <div class="fitem" style="float: right; padding-left: 4px;">
                        <label>Offered Amount:</label>
                        <input id="txtapp_oamount" oninput="changePriceOff();" style="width: 95px;" type="text" class="easyui-validatebox" />
                    </div>
                </div>
                <div style="float: left; padding-left: 3%;">
                </div>
                <div style="clear: both"></div>
                <div class="fitem">
                    <label>App Status:</label>
                    <input class="easyui-combobox" id="cmbapp_lastresult" style="width: 304px;"
                        data-options="panelWidth: 304, 
                        valueField: 'ResultDescription',  
                        textField: 'ResultDescription',
                        url: '/WebServices/ApplicationInfo.ashx?method=LastResultData',
                        onLoadSuccess:function(){
                          window.onbeforeunload =null;
                        }" />
                </div>
                <div class="fitem">
                    <label>Await Docs:</label>
                    <select class="easyui-combogrid" id="cmbapp_awaitdocs" style="width: 304px" data-options="
                    panelWidth: 304,
                    multiple: true,
                    idField: 'AwaitedDocs',
                    textField: 'AwaitedDocs',
                    editable:true,
                    url: '/WebServices/ApplicationInfo.ashx?method=BindAwaitDocs',
                    columns: [[  
                        {field:'ck',checkbox:true},
                        {field:'AwaitedDocs',width:80},      
                    ]],  
                    onSelect:getSelections, 
                    onUnselect:getUnselected,   
                    fitColumns: true,
                    onLoadSuccess:function(){
                          window.onbeforeunload =null;
                        }">
                    </select>
                </div>
                <div class="fitem">
                    <label>Folder:</label>

                    <input type="text" id="txtapp_folder" onchange="setfolderValue()" runat="server" style="width: 280px" class="easyui-validatebox" />
                    <input type="hidden" id="hdn_txtapp_folder" runat="server">

                    <a runat="server" id="folderValue" style="height: 22px;"></a>
                </div>
                <div style="float: left;">
                    <div class="fitem" style="float: left;">
                        <label>Vehicle :</label>
                        <select id="cmbVehicle" data-options="panelHeight:'auto'" class="easyui-combobox" style="width: 94px;">
                            <option value="0">0</option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                        </select>
                    </div>
                    <div class="fitem" style="float: right; padding-left: 53px;">
                        <label style="width: 60px;">Property </label>
                        <select id="cmbProperty" data-options="panelHeight:'auto'" class="easyui-combobox" style="width: 95px;">
                            <option value="0">0</option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                        </select>
                    </div>

                    <div class="fitem">
                        <label style="width: 110px">Car Owner Check:</label>
                        <input type="checkbox" id="chkcarOwner" value="" />
                    </div>
                </div>
                <div class="fitem">
                    <label>Create Date:</label>
                    <input type="text" id="txtCreatedDate" readonly="yes" style="background-color: LightGray; width: 135px;" class="easyui-validatebox" />
                </div>
            </div>
            <div class="equal_div" style="width: 25%; padding-left: 3%;">
                <div data-options="region:'east',split:true,border:false" class="fitem">
                    <label style="display: inline-block; width: 100px">Loan Purpose:</label>
                    <select id="cmbLoanPurpose" data-options="panelHeight:'auto'" class="easyui-combobox" style="width: 95px;">
                        <option selected="selected">-Select-</option>
                        <option value="Personal">Personal</option>
                        <option value="Business">Business</option>
                        <option value="SACC">SACC</option>
                    </select>
                </div>

                <div class="fitem">
                    <label>Note:</label>
                </div>
                <textarea id="txtMemoApp" style="font-family: Arial,Helvetica,sans-serif; width: 100%; height: 140px;"></textarea>
            </div>
        </div>
        <div data-options="region:'east',split:true,border:false" style="padding-left: 3%;" class="equal_div">
            <div class="fitem">
                <label>Application No:</label>
                <input id="txtappno" readonly="yes" type="text" class="easyui-validatebox" />
            </div>
            <div class="fitem">
                <label>Loan No:</label>
                <input id="txtapp_loanno" class="easyui-validatebox" />
            </div>

            <div class="fitem">
                <label>Loan Status :</label>
                <select id="cmbLoanStatus" data-options="panelHeight:'auto'" class="easyui-combobox" style="width: 100px;">
                    <option value="selected">--Select--</option>
                    <option value="Opening">Opening</option>
                    <option value="Active">Active</option>
                    <option value="Close">Close</option>
                </select>
            </div>

            <div class="fitem">
                <label>Outsource Lender:</label>
                <input class="easyui-combobox" id="cmbOutSourceLender" style="width: 140px" data-options="  
                    panelWidth: 230, 
                    valueField: 'OutSourceLender',  
                    textField: 'OutSourceLender',  
                    url: '/WebServices/ApplicationInfo.ashx?method=OutSrcLender'" />
            </div>
            <div class="fitem">
                <label>Referrer:</label>
                <input class="easyui-combobox" id="cmbReferrer" style="width: 140px" data-options="  
                panelWidth: 230, 
                valueField: 'Referrer',  
                textField: 'Referrer',  
                url: '/WebServices/ApplicationInfo.ashx?method=ReferrerData'" />

            </div>
            <div class="fitem">
                <label>Came From:</label>
                <input type="text" id="txtComesFrom" readonly="yes" style="background-color: LightGray; width: 100px;" class="easyui-validatebox" />
            </div>
            <label id="lblDelInfo" style="font-size: 14px; color: red;"></label>

        </div>

        <div id="dlgSuccess" class="easyui-dialog" title="Success" style="width: 300px; height: 120px" closed="true" resizable="false" modal="true">
            <h4 style="text-align: center">Application Profile Save Successfully</h4>
            <img id="successProgress" style="margin-left: 20px" src="/Media/loading.gif" />
            <label id="lblSuccessTimeOut" style="margin-left: 20px">5</label>
        </div>
        <div id="wndRemoveAppForm" class="easyui-window" title="Remove Duplicate" data-options="iconCls:'icon-save',modal:true,closed:true" style="width: 400px; height: 200px; padding: 5px;">
            <div>
                <label style="width: 193px; padding-top: 5px; padding-left: 96px; font-weight: bold;">Remove the duplicate application</label>
            </div>
            <div class="fitem">
                <label style="width: 193px; padding-top: 20px; padding-left: 12px">Current Application Number Is:</label>
                <label style="color: red" id="lblCurrAppNum"></label>
            </div>
            <div class="fitem">
                <label style="width: 193px; padding-left: 12px">New Application Number Is:</label>
                <input id="txtNewAppNum" type="text" name="txtNewAppNum" class="easyui-validatebox" />
            </div>
            <div style="padding-left: 209px; padding-top: 3px;">
                <a href="javascript:void(0)" class="easyui-linkbutton" onclick="RemoveDuplicates()">Ok</a>
            </div>
            <div style="padding-top: 10px;">
                <label id="lblNotExist" style="font-weight: bold; padding-left: 96px; color: red;"></label>
            </div>

        </div>
    </div>
</div>

<div id="dlgDelApp" class="easyui-dialog" title="Confirm" style="width: 300px; height: 160px" closed="true" resizable="false" modal="true">
    <h4 style="text-align: center">Are you sure want to delete this Application?</h4>
    <div class="fitem" style="float: left; padding: 10px; margin-top: 10px">
        <a id="lnkdelApps" href="javascript:void(0)" class="easyui-linkbutton" onclick="deleteApplication()" disabled="true">OK</a>
        <a id="lnkcnclApps" href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#dlgDelApp').dialog('close')" disabled="true">Cancel</a>
        <span id="spnanimates">
            <img id="deleteProgress" style="margin-left: 20px" src="/Media/loading.gif" />
            <label id="lbltmOut" style="margin-left: 20px">5</label>
        </span>
    </div>
</div>

<script type="text/javascript">
    var awaitVal;
    var isSACCapp = false;
    var isOtherapp = false;
    var loanPurpose = '';
    function getSelections() {
        var ss = [];
        var r = $('#cmbapp_awaitdocs').combogrid('grid');
        var rows = r.datagrid('getSelections');

        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            ss.push(row.AwaitedDocs);
        }
        awaitVal = ss.join(',');
    }

    function getUnselected() {
        awaitVal = '';
    }
    function showPrompt() {
        return 'You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?';
    }
    function setfolderValue() {
        $('#ContentPlaceHolder1_appProfile_hdn_txtapp_folder').val($('#ContentPlaceHolder1_appProfile_txtapp_folder').val());
        document.getElementById("ContentPlaceHolder1_appProfile_folderValue").href = "file:///" + $('#ContentPlaceHolder1_appProfile_txtapp_folder').val();
    }
    function enableWindowUnload() {

        $('#cmbVehicle').combobox({
            onSelect: function (n, o) {
                window.onbeforeunload = showPrompt;
            }
        });

        $('#cmbLoanStatus').combobox({
            onSelect: function (n, o) {
                window.onbeforeunload = showPrompt;
            }
        });

        $('#cmbProperty').combobox({
            onSelect: function (n, o) {
                window.onbeforeunload = showPrompt;
            }
        });

        $('#txtMemoApp').change(function () {
            window.onbeforeunload = showPrompt;
        });

        $('#txtapp_loanno').change(function () {
            window.onbeforeunload = showPrompt;
        });

        $('#txtapp_damount').change(function () {
            window.onbeforeunload = showPrompt;
        });

        $('#txtapp_oamount').change(function () {
            window.onbeforeunload = showPrompt;
        });


        $('#chkcarOwner').change(function () {
            window.onbeforeunload = showPrompt;
        });

        //$('#checkUnsub').change(function () {
        //    window.onbeforeunload = showPrompt;
        //});


        $('#cmbLoanPurpose').combobox({
            onSelect: function (n, o) {
                if (loanPurpose != 'SACC' && $('#cmbLoanPurpose').combobox('getValue') == 'SACC')
                    isSACCapp = true;
                else if (loanPurpose == 'SACC' && $('#cmbLoanPurpose').combobox('getValue') != 'SACC')
                    isOtherapp = true;

                window.onbeforeunload = showPrompt;

            }
        });
        $('#cmbapp_lastresult').combobox({
            onSelect: function (n, o) {
                window.onbeforeunload = showPrompt;
            }
        });
        $('#cmbOutSourceLender').combobox({
            onSelect: function (n, o) {
                window.onbeforeunload = showPrompt;
            }
        });
        //$('#cmbapp_awaitdocs').combogrid({
        //    onSelect: function (n, o) {
        //        window.onbeforeunload = showPrompt;
        //    }
        //});
        $('#cmbReferrer').combobox({
            onSelect: function (n, o) {
                window.onbeforeunload = showPrompt;
            }
        });

    }

    function changePrice() {
        $('#txtapp_damount').formatCurrency();
    }

    function changePriceOff() {
        $('#txtapp_oamount').formatCurrency();
    }
    function getNavigation() {
        if (document.referrer.indexOf('ApplicationMain.aspx') > 0)
            $('#spnNavigation').html('<a href="javascript: history.go(-1)">List</a> >> ');
        else if (document.referrer.indexOf('ContactDetail.aspx') > 0)
            $('#spnNavigation').html('<a href="javascript: history.go(-1)">Client Profile</a> >> ');
        else if (document.referrer.indexOf('GroupList.aspx') > 0)
            $('#spnNavigation').html('<a href="javascript: history.go(-1)">Group</a> >> ');
        else if (document.referrer.indexOf('ApplicationDetail.aspx') > 0)
            $('#spnNavigation').html('<a href="javascript: history.go(-1)">Application Profile</a> >> ');
        else
            $('#spnNavigation').html('<a href="javascript: history.go(-1)">Back</a> >> ');
        $('#spnNavigation').html($('#spnNavigation').html() + 'Application Profile');
    }
    function setComboboxClick() {
        $('#cmbapp_lastresult').combobox('textbox').bind('click', function () {
            $('#cmbapp_lastresult').combobox('showPanel');
        });

        $('#cmbReferrer').combobox('textbox').bind('click', function () {
            $('#cmbReferrer').combobox('showPanel');
        });

        $('#cmbLoanStatus').combobox('textbox').bind('click', function () {
            $('#cmbLoanStatus').combobox('showPanel');
        });

        $('#cmbProperty').combobox('textbox').bind('click', function () {
            $('#cmbProperty').combobox('showPanel');
        });

        $('#cmbVehicle').combobox('textbox').bind('click', function () {
            $('#cmbVehicle').combobox('showPanel');
        });

        $('#cmbapp_awaitdocs').combogrid('textbox').bind('click', function () {
            $('#cmbapp_awaitdocs').combogrid('showPanel');
        });
        $('#cmbLoanPurpose').combobox('textbox').bind('click', function () {
            $('#cmbLoanPurpose').combobox('showPanel');
        });
        $('#cmbOutSourceLender').combobox('textbox').bind('click', function () {
            $('#cmbOutSourceLender').combobox('showPanel');
        });
    }
    function setApplicantNames(appid) {
        $.ajax({
            url: "/WebServices/ApplicationInfo.ashx?method=ShowAppNames",
            data: { app_id: appid },
            success: function (data) {
                if (data == '0')
                    return;
                else if (data == '1') {
                    $.messager.alert('Morgan CRM', '<span style="color:red"> Error while fetching Applicant Names  </span>');
                }
                else {
                    var arrObj = $.parseJSON(data);
                    var len = arrObj.length;
                    var fullname = '';
                    if (len == 1) {
                        $('#ContentPlaceHolder1_appProfile_hdnContactID').val(arrObj[0].ContactID);
                        fullname = '<a target="_self" href="/Pages/Contact/ContactDetail.aspx?contact_id=' + arrObj[0].ContactID + '"><span style="font-weight:bold;color:red;font-family:Arial;font-size:14px;">' + arrObj[0].FullName + '</span></a>' +
                                        '<span style="font-family: Arial; font-size: 12px; font-weight:bold">\'S Application Profile </sapn>';
                        document.getElementById("spnFullName").innerHTML = fullname;
                        document.title = arrObj[0].FullName + ' - App Profile';
                    }
                    else if (len == 2) {
                        $('#ContentPlaceHolder1_appProfile_hdnContactID').val(arrObj[0].ContactID);
                        fullname = '<a target="_self" href="/Pages/Contact/ContactDetail.aspx?contact_id=' + arrObj[0].ContactID + '"><span style="font-weight:bold;color:red;font-family:Arial;font-size:14px;">' + arrObj[0].FullName + '</span></a>';

                        fullname += '&nbsp <b> & </b> &nbsp <a target="_self" href="/Pages/Contact/ContactDetail.aspx?contact_id=' + arrObj[1].ContactID + '"><span style="font-weight:bold;color:red;font-family:Arial;font-size:14px;">' + arrObj[1].FullName + '</span></a>' +
                                       '<span style="font-family: Arial; font-size: 12px; font-weight:bold">\'S Application Profile </sapn>';
                        document.getElementById("spnFullName").innerHTML = fullname;
                        document.title = arrObj[0].FullName + ' & ' + arrObj[1].FullName + ' - App Profile';
                    }
                    else if (len == 3) {
                        $('#ContentPlaceHolder1_appProfile_hdnContactID').val(arrObj[0].ContactID);
                        fullname = '<a target="_self" href="/Pages/Contact/ContactDetail.aspx?contact_id=' + arrObj[0].ContactID + '"><span style="font-weight:bold;color:red;font-family:Arial;font-size:14px;">' + arrObj[0].FullName + '</span></a>';
                        fullname += ' &nbsp  <b> & </b> &nbsp <a target="_self" href="/Pages/Contact/ContactDetail.aspx?contact_id=' + arrObj[1].ContactID + '"><span style="font-weight:bold;color:red;font-family:Arial;font-size:14px;">' + arrObj[1].FullName + '</span></a>';
                        fullname += '  &nbsp <b> & </b> &nbsp <a target="_self" href="/Pages/Contact/ContactDetail.aspx?contact_id=' + arrObj[2].ContactID + '"><span style="font-weight:bold;color:red;font-family:Arial;font-size:14px;">' + arrObj[2].FullName + '</span></a>' +
                                    ' <span style="font-family: Arial; font-size: 12px; font-weight:bold">\'S Application Profile </sapn>';
                        document.getElementById("spnFullName").innerHTML = fullname;
                        document.title = arrObj[0].FullName + ' & ' + arrObj[1].FullName + ' & ' + arrObj[2].FullName + ' - App Profile';
                    }
                }
            }
        });
    }
    function getQuerystring(key, defaultValue) {
        if (defaultValue == null) defaultValue = "";
        key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
        var qs = regex.exec(window.location.href);
        if (qs == null)
            return defaultValue;
        else {
            return qs[1];
        }
    }

    function saveAllData() {

        if (getQuerystring('type', '') != 'SACC') {

            if ($('#ContentPlaceHolder1_appProfile_hdnVerification').val() == 'true')
                UpdateApplicantDatas();
            if ($('#ContentPlaceHolder1_appProfile_hdnAssessment').val() == 'true')
                SaveAssesmentData();

            setTimeout(function () {
                saveApplicationData();
            }, 100);
        }
        else {
            if ($('#ContentPlaceHolder1_appProfile_hdnMC_status').val() == 'active') {
                saveApplicationData();
                $.messager.alert('Morgan CRM', '<span style="color:red;font-weight:bold">  Loan is Active can\'t update SACC Verification and Contract Data ! </span>');
                return;
            }
            else {
                saveSACCVerificationData();
                saveApplicationData();
            }
        }
    }
    var OperatorId = '';
    $(document).ready(function () {
        OperatorId = document.getElementById('hdnNodeVal').value;
        getNavigation();
        selectApplicationData();
        setApplicantNames(getQuerystring('app_id', ''));
        $('#lblCurrAppNum').html(getQuerystring('app_id', 0));

        if (getQuerystring('type', '') == 'SACC') {
            $('#lnkCombine').linkbutton('disable');
        }
        else {
            $('#lnkCombine').linkbutton('enable');
        }


        //Change color of combobox:
        setColorForCombobox();

        $('#dlgDelApp').dialog({
            onOpen: function () {
                startCounter(5);
            },
            onClose: function () {
                $('#lnkdelApps').linkbutton('disable');
                $('#lnkcnclApps').linkbutton('disable');
                $('#spnanimates').show();
                $('#lbltmOut').html('');
            }
        });

        setComboboxClick();
        enableWindowUnload();
    });
    $('#dlgSuccess').dialog({
        onOpen: function () {
            startSuccessCounter(5);
        },
        onClose: function () {
            $('#lblSuccessTimeOut').html('');
        }
    });

    function popupWinCenter(URL, title, w, h) {
        var left = (screen.width / 2) - (w / 2);
        var top = (screen.height / 2) - (h / 2);
        var strfeatures = 'width=' + w + ', height= ' + h + ', top=' + top + ',left=' + left;
        var newWin = window.open(URL, title, strfeatures);
        newWin.onload = function () { window.focus(); }
        newWin.onunload = function () { $('#dgApplicationHistory').datagrid('reload'); }
    }


    $(document).keydown(function (event) {
        if ((event.which == 83 || event.which == 115) && (event.ctrlKey || event.metaKey) || (event.which == 19)) {
            event.preventDefault();
            saveAllData();
            return false;
        }
        else if ((event.which == 72 || event.which == 104) && (event.ctrlKey || event.metaKey) || (event.which == 19)) {
            event.preventDefault();
            // do stuff - ctrl + h
            setTimeout(function () {
                popupWinCenter('/Pages/History.aspx?type=Application&Operation=new&app_id=' + getQuerystring('app_id', 0) + '&Theme=' + getCookie('Theme'), 'New Application history', 650, 610);
            }, 100);
            return false;
        }
        return true;
    });
    function startSuccessCounter(limit) {
        setTimeout(function () {
            if (limit == 0) {
                $('#dlgSuccess').dialog('close');
            }
            else {
                $('#lblSuccessTimeOut').html(limit);
                startSuccessCounter(limit - 1);
            }
        }, 100);
    }
    function deleteApplication() {
        window.onbeforeunload = null;
        var app_id = getQuerystring('app_id', 0);
        if (app_id > 0) {
            $.ajax({
                url: '/WebServices/ApplicationInfo.ashx?method=deleteApplication',
                data: { app_id: app_id },
                success: function (data) {
                    $('#dlgDelApp').dialog('close');
                    if (data == 'active')
                        $.messager.alert('Morgan CRM', '<span style="color:red;font-weight:bold">  Loan is Active,Application can not be deleted ! </span>');
                    else if (data == 'deleted')
                        saveHistoryForDelete(app_id);
                    else if (data == "Loan is exist you can not delete this application.")
                        $.messager.alert('Morgan CRM', '<span style="color:red;font-weight:bold"> ' + data + '</span>');
                    else if (data == "Check list is exist you can not delete this application.")
                        $.messager.alert('Morgan CRM', '<span style="color:red;font-weight:bold"> ' + data + '</span>');
                    else if (data == "Loan and check list is exist you can not delete this application.")
                        $.messager.alert('Morgan CRM', '<span style="color:red;font-weight:bold">' + data + ' </span>');
                    else if (data == '0')
                        $.messager.alert('Morgan CRM', '<span style="color:red;font-weight:bold"> Error while Deleting Application  </span>');
                }
            });
        }
    }
    var EmailVal = [];
    var strEmail;

    var MobileVal = [];
    var strMobile;
    function selectApplicationData() {
        $.ajax({
            url: "/WebServices/ApplicationInfo.ashx?method=SelectApplicationProfileData",
            data: { 'app_id': getQuerystring('app_id', ''), 'OperatorID': OperatorId },
            success: function (data) {
                if (data == "[]") {
                    $("#cmbapp_awaitdocs").combogrid('setValue', 'None doc');
                    $("#cmbapp_lastresult").combogrid('setValue', '99:Imported-Yet To Allocate');
                    $("#cmbReferrer").combobox('setValue', '');
                    $("#cmbVehicle").combobox('setValue', '');
                    $("#cmbProperty").combobox('setValue', '');
                    $("#cmbOutSourceLender").combobox('setValue', '');
                }
                else {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        $('#txtapp_damount').val(rec.DesiredAmount).formatCurrency();
                        $('#txtapp_oamount').val(rec.OfferedAmount).formatCurrency();;
                        $('#cmbapp_lastresult').combobox('setValue', rec.app_result);
                        $('#txtCreatedDate').val(rec.cdate);
                        $('#cmbLoanPurpose').combobox('setValue', rec.PurposeSummary);
                        loanPurpose = rec.PurposeSummary;
                        $('#cmbLoanStatus').combobox('setValue', rec.status);
                        if (rec.status == 'Active')
                            $('#btnDelete').linkbutton('disable');
                        else
                            $('#btnDelete').linkbutton('enable');

                        $('#txtComesFrom').val(rec.comesfrom);

                        $('#cmbVehicle').combobox('setValue', rec.amountMoto);
                        $('#cmbProperty').combobox('setValue', rec.amoutProperties);
                        $('#txtMemoApp').val(rec.Memo);
                        $('#txtapp_loanno').val(rec.LoadNo);
                        $('#cmbOutSourceLender').combobox('setValue', rec.OutSrcLenderVal);
                        $('#cmbReferrer').combobox('setValue', rec.ReferrerVal);
                        EmailVal.push(rec.Email);
                        strEmail = EmailVal[0];
                        $('#hdnEmail').val(rec.Email);

                        MobileVal.push(rec.Mobile);
                        strMobile = MobileVal[0];
                        $('#hdnMobile').val(strMobile);
                        $('#txtappno').val(rec.app_id)

                        var awaitd = rec.TextAwaitDoc;
                        var awaitVal = awaitd.split(',');
                        $("#cmbapp_awaitdocs").combogrid('setValues', awaitVal);
                        $('#ContentPlaceHolder1_appProfile_hdnMC_status').val(rec.MC_status);

                        if (rec.IsCarOwner == 0)
                            document.getElementById("chkcarOwner").checked = false;
                        else
                            document.getElementById("chkcarOwner").checked = true;

                        if (rec.deletedFlag == "1") {
                            $('#lblDelInfo').html("Deleted");
                        }
                    });
                }
            }
        });
    }

    function saveApplicationData() {
        window.onbeforeunload = null;
        var app_id = getQuerystring('app_id', 0);
        var ContactID = getQuerystring('contact_id', 0);
        var desiredAmount = $("#txtapp_damount").val().replace(/,/g, '').replace('$', '');
        var offeredAmount = $("#txtapp_oamount").val().replace(/,/g, '').replace('$', '');

        var resultDescription = $("#cmbapp_lastresult").combobox('getValue');
        var outSrcLenderVal = $("#cmbOutSourceLender").combobox('getValue');
        var referrerVal = $("#cmbReferrer").combobox('getValue');
        var loadNo = $("#txtapp_loanno").val();
        var awaitDocs = $("#cmbapp_awaitdocs").combogrid('getText');

        var folder = $("#ContentPlaceHolder1_appProfile_txtapp_folder").val().replace(/:/g, "&");
        var motorCount = $('#cmbVehicle').combobox('getValue');
        var amoutProperties = $("#cmbProperty").combobox('getValue');
        var loanpurpose = $('#cmbLoanPurpose').combobox('getValue');
        var v_loanstatus = $('#cmbLoanStatus').combobox('getValue');

        var carOwner = '';
        if (document.getElementById('chkcarOwner').checked == true)
            carOwner = 1;
        else
            carOwner = 0;

        var memo = $('#txtMemoApp').val();
        var user = $('#ContentPlaceHolder1_appProfile_hdnUserName').val();

        if (app_id <= 0 && ContactID > 0) {
            // New Application
            var NoInApplication = "1";
            var CombineApp = "";
            var NoInApplications = "1";

            $.ajax({
                url: '/WebServices/ApplicationInfo.ashx?method=saveNewApplicationProfile',
                data: {
                    ContactID: ContactID, NoInApplication: NoInApplication, CombineApp: CombineApp, DesiredAmount: desiredAmount, OfferedAmount: offeredAmount, app_result: resultDescription, LoadNo: loadNo,
                    NoInApplications: NoInApplications, Folder: folder, amountMoto: motorCount, amoutProperties: amoutProperties, TextAwaitDoc: awaitDocs, LoanStatus: v_loanstatus,
                    purposeSummary: loanpurpose, memo: memo, outSrcLenderVal: outSrcLenderVal, referrerVal: referrerVal, Operator: user, IsCarOwner: carOwner
                },
                success: function (data) {
                    //$('#dgApplicationHistory').datagrid('reload');
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        if (rec.app_id != '' || rec.app_id == null) {
                            $('#dlgSuccess').dialog('open');
                            setTimeout(function () {
                                if (loanpurpose == "SACC")
                                    window.location.href = "/Pages/Application/ApplicationDetailSACC.aspx?app_id=" + rec.app_id + "&type=" + loanpurpose;
                                else
                                    window.location.href = "/Pages/Application/ApplicationDetail.aspx?app_id=" + rec.app_id + "&type=" + loanpurpose;
                            }, 100);
                        }
                    });
                }
            });
        }
        else {
            $.ajax({
                url: "/WebServices/ApplicationInfo.ashx?method=UpdateApplicationProfile",
                data: {
                    'appid': app_id, 'desiredAmount': desiredAmount, 'offeredAmount': offeredAmount, 'resultDescription': resultDescription,
                    'loadNo': loadNo, 'folder': folder, 'motorCount': motorCount, 'propertyCount': amoutProperties, 'TextAwaitDoc': awaitDocs,
                    'purposeSummary': loanpurpose, 'memo': memo, 'outSrcLenderVal': outSrcLenderVal, 'LoanStatus': v_loanstatus,
                    'referrerVal': referrerVal, 'oprator': user, 'IsCarOwner': carOwner
                },
                success: function (result) {

                    if (isSACCapp == true)
                        window.location.href = "/Pages/Application/ApplicationDetailSACC.aspx?app_id=" + app_id + "&type=SACC";
                    else if (isOtherapp == true)
                        window.location.href = "/Pages/Application/ApplicationDetail.aspx?app_id=" + app_id + "&type=" + loanpurpose;
                    else {
                        $('#dlgSuccess').dialog('open');
                        $('#dgApplicationHistory').datagrid('reload');

                        if (getQuerystring('type', '') == 'SACC') {
                            bindVerificationData();
                            //var tab = $('#MainTab').tabs('getTab', 'SACC'); // get selected panel
                            //tab.panel('refresh', '/Pages/Application/ApplicationSACC.aspx?app_id=' + app_id);
                        }
                        //else {
                        //    var tab = $('#MainTab').tabs('getTab', 'Verification Checklist'); // get selected panel
                        //    tab.panel('refresh', '/Pages/Application/VerificationChecklist.aspx?app_id=' + app_id);
                        //}
                    }
                }
            });
        }
    }


    function saveHistoryForDelete(appid) {
        var currentDate = new Date()
        var day = currentDate.getDate()
        var month = currentDate.getMonth() + 1
        var year = currentDate.getFullYear()
        var HistoryDate = month + "/" + day + "/" + year;

        var currentTime = new Date()
        var hours = currentTime.getHours()
        var minutes = currentTime.getMinutes()
        var seconds = currentTime.getSeconds();
        var HistoryTime = hours + ':' + minutes + ':' + seconds;

        var Action = 'Delete Operation(system)';
        var Operator = $('#ContentPlaceHolder1_appProfile_hdnUserName').val();
        var Description = "This application has been delete.";

        $.ajax({
            type: "Post",
            data: { HistoryType: 'Application', contactid: '0', hdate: HistoryDate, htime: HistoryTime, action: Action, user: Operator, description: Description, appid: appid },
            url: "/WebServices/History.ashx?method=saveNewHistory",
            success: function (result) {
                window.location.href = '/Pages/Application/ApplicationMain.aspx';
            }
        });
    }

    function showDirectory() {
        document.getElementById('ContentPlaceHolder1_appProfile_txtapp_folder').value = window.showModalDialog("/Pages/BrowseFolder.aspx", 'Browse Files and Folder', "dialogHeight: 490px; dialogWidth: 400px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No;");
        window.returnValue = document.getElementById('ContentPlaceHolder1_appProfile_txtapp_folder').value
        return false;
    }
    function setColorForCombobox() {
        var elements = document.getElementsByClassName('combo-text');

        for (var i = 0, l = elements.length; i < l; i++) {
            elements[2].style.backgroundColor = "rgb(255,255,198)";// app result Yellow
            elements[3].style.backgroundColor = "rgb(255,255,198)";// await docs Yellow
            elements[6].style.backgroundColor = "rgb(255,195,198)";// Loan purpose Pink
        }

        elements = '';
        elements = document.getElementsByClassName('datagrid-view2');
        for (var i = 0, l = elements.length; i < l; i++) {
            elements[0].style.backgroundColor = "rgb(255,255,198)";// Await Docs Yellow
        }
        elements = '';
        elements = document.getElementsByClassName('combo-panel panel-body panel-body-noheader');
        for (var i = 0, l = elements.length; i < l; i++) {
            elements[2].style.backgroundColor = "rgb(255,255,198)";// App_result Yellow
            elements[5].style.backgroundColor = "rgb(255,195,198)";// Loan Purpose pink
        }
    }

    function startCounter(limit) {
        setTimeout(function () {
            if (limit == 0) {
                $('#lnkdelApps').linkbutton('enable');
                $('#lnkcnclApps').linkbutton('enable');
                $('#spnanimates').hide();
            }
            else {
                $('#lbltmOut').html(limit);
                startCounter(limit - 1);
            }
        }, 500);
    }

    function RemoveDuplicates() {
        var ApplicationId = getQuerystring('app_id', 0);
        var AppFormId = $("#txtNewAppNum").val();
        $.ajax({
            url: "/WebServices/ApplicationInfo.ashx?method=RemoveDuplicateApp",
            data: { ApplicationId: ApplicationId, AppFormId: AppFormId },
            success: function (result) {
                if (result == '1')
                    $.messager.alert('Morgan CRM', '<span style="color:red">  Error while removing Duplicate Applications </span>');
                else {
                    SaveHistoryRemoveDuplicatApp(ApplicationId);
                    $("#txtNewAppNum").val('');
                    $('#wndRemoveAppForm').dialog('close');
                }
            },
            error: function (result) {
                var errorMsg = "The appform " + AppFormId + " is not exist";
                $('#lblNotExist').html(errorMsg);
                $("#txtNewAppNum").val('');
            }
        });
    }

    function SaveHistoryRemoveDuplicatApp(app_id) {
        var AppFormId = $("#txtNewAppNum").val();
        var currentDate = new Date()
        var day = currentDate.getDate()
        var month = currentDate.getMonth() + 1
        var year = currentDate.getFullYear()
        var HistoryDate = month + "/" + day + "/" + year;

        var currentTime = new Date()
        var hours = currentTime.getHours()
        var minutes = currentTime.getMinutes()
        var seconds = currentTime.getSeconds();
        var HistoryTime = hours + ':' + minutes + ':' + seconds;

        var Action = 'Remove Duplicate';
        var Operator = document.getElementById('ContentPlaceHolder1_appProfile_hdnUserName').value;;
        var Description = "Remove the duplicate ApplicationID=" + "<span style='color:red'>" + app_id + '</span>' + " with new ApplicationID=" + "<span style='color:green'>" + AppFormId + '</span>' + "";

        $.ajax({
            url: "/WebServices/History.ashx?method=saveNewHistory",
            data: {
                HistoryType: 'Application', contactid: '0', hdate: HistoryDate, htime: HistoryTime, action: Action,
                user: Operator, description: Description, appid: app_id
            },
            success: function (result) {
                $('#dgApplicationHistory').datagrid('reload');
            }
        });

        $.ajax({
            url: "/WebServices/History.ashx?method=saveNewHistory",
            data: {
                HistoryType: 'Application', contactid: '0', hdate: HistoryDate, htime: HistoryTime, action: Action,
                user: Operator, description: Description, appid: $('#txtNewAppNum').val()
            },
            success: function (result) {
                $('#dgApplicationHistory').datagrid('reload');
            }
        });
    }

</script>
